class SizeAdapt {
  constructor(opt) {
    let defultOpt = {
      sizeEqualRatio: false, //是否等比缩放页面
      w: 1920, // 默认宽度
      h: 1080, // 默认高度
      wrapSelector: '', // 顶层容器 默认body
      domSelector: 'body', // 默认绑定dom节点，进行缩放的节点
      left: 'm', //'l','m','r' 定位位置 默认水平居中
      top: 'm', //'t' 'm','b' 定位位置 默认垂直居中
      isResize: true
    }
    Object.assign(this, defultOpt, opt)
    this.isResize && window.addEventListener('resize', this.resize.bind(this))
  }
  resize() {
    let wrap = document.querySelector(this.wrapSelector)
    let view = document.querySelector(this.domSelector)

    view.style.position = 'absolute'
    view.style.width = this.w + 'px'
    view.style.height = this.h + 'px'

    let dw = this.wrapSelector ? wrap.clientWidth : document.body.clientWidth
    let dh = this.wrapSelector ? wrap.clientHeight : document.body.clientHeight
    let minRatio = Math.min(dw / this.w, dh / this.h)
    let left, top, right, bottom

    if (this.sizeEqualRatio) {
      view.style.transform = 'scale(' + minRatio + ')'
      switch (this.top) {
        case 'm':
          top = (dh - this.h) / 2 + 'px'
          break
        case 't':
          top = (this.h * (minRatio - 1)) / 2 + 'px'
          break
        case 'b':
          bottom = (this.h * (minRatio - 1)) / 2 + 'px'
      }
      switch (this.left) {
        case 'm':
          left = (dw - this.w) / 2 + 'px'
          break
        case 'l':
          left = (this.w * (minRatio - 1)) / 2 + 'px'
          break
        case 'r':
          right = (this.w * (minRatio - 1)) / 2 + 'px'
      }
    } else {
      view.style.transform = 'scale(' + dw / this.w + ',' + dh / this.h + ')'
      left = (this.w * (dw / this.w - 1)) / 2 + 'px'
      top = (this.h * (dh / this.h - 1)) / 2 + 'px'
    }

    top ? (view.style.top = top) : (view.style.bottom = bottom)
    left ? (view.style.left = left) : (view.style.right = right)
  }
}

export default SizeAdapt
